package cn.zsb.proxy.cglibProxy;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

public class ProxyFactory implements MethodInterceptor {
    //目标对象
    private Object target;

    public ProxyFactory(Object target){
        this.target = target;
    }

    //获取代理对象实例
    public Object getProxyInstance(){
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(target.getClass());//设置目标对象
        enhancer.setCallback(this);//当前对象回调
        return enhancer.create();//创建代理对象
    }

    @Override
    public Object intercept(
            Object o,//代理对象
            Method method,//执行的方法
            Object[] args,//方法参数
            MethodProxy methodProxy//代理方法
    ) throws Throwable {
        System.out.println("cglib动态代理开始");
        Object returnVal = method.invoke(target, args);
        System.out.println("cglib动态代理结束");
        return returnVal;
    }

}
